//
//  EditProfilView.m
//  VivaModa
//
//  Created by Sergey on 3/2/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "EditProfilView.h"
#import "register_cell.h"


@interface EditProfilView (){
    Boolean keyboardIsShowing;
    CGRect keyboardBounds;
    NSArray *array_step_edit_data;
    
    NSArray *array_step_edit_password;
    
    UITextField *test_textField;
}
@property(nonatomic,retain) UILabel *title_label;
@property (strong, nonatomic) NSMutableArray *sortedArrayRegion;
@property (strong, nonatomic) NSMutableArray *sortedArrayCountry;
@property (strong, nonatomic) NSArray *dataLocation;

- (void)resizeViewControllerToFitScreen;
@end

@implementation EditProfilView
@synthesize title_label;
@synthesize choose_group;
@synthesize pickerView;
@synthesize tableView;
@synthesize sortedArrayRegion;
@synthesize sortedArrayCountry;
@synthesize dataLocation;
@synthesize connection_locate;
@synthesize locateData;
@synthesize needReload;
@synthesize button_resave;

@synthesize customer_data;
@synthesize connection_customer_data;
@synthesize send_data_user;
@synthesize connection_send_data;

bool current_change_data;


bool showed_picker;

NSString *text_region;
NSString *text_strana;

NSString *text_name;
NSString *text_second_name;
NSString *text_email;
NSString *text_adress;
NSString *text_town;
NSString *text_telephone;
NSString *text_old_pass;
NSString *text_new_pass;
NSString *text_new_pass_comf;
bool subscribe_user;


int id_button;

int current_id_country_ = -1;
int last_country_id_ = 0;/// что б небыло в Украине Москвы
int last_zone_id_ = 0;///

NSString *parsed_password;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    
    
   // NSLog(@"user id = %i",[Singleton sharedMySingleton].user_id);
    
    if (needReload) {
        needReload = NO;
        [self parseCustomerData];
    }
    
    
    current_change_data = YES;
    self.choose_group.selectedSegmentIndex = 0;
    [self.tableView reloadData];
    
    text_region = @"";
    text_strana = @"";
    subscribe_user = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}


- (void)viewWillDisappear:(BOOL)animated {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    [self addCustomBackButton];
    sortedArrayRegion = [[NSMutableArray alloc] initWithCapacity:1];
    sortedArrayCountry = [[NSMutableArray alloc] initWithCapacity:1];
    [self getLocationData];
    
    
    self.title_label = [[UILabel alloc] initWithFrame:CGRectZero];
    self.title_label.backgroundColor = [UIColor clearColor];
    self.title_label.font = [UIFont fontWithName:@"Arial" size:12];
    self.title_label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    self.title_label.textAlignment = UITextAlignmentCenter;
    self.title_label.textColor = [UIColor whiteColor]; // change this color
    self.title_label.numberOfLines = 2;
    
    self.title_label.text = @"Редактирование личных данных";
    
    self.navigationItem.titleView = self.title_label;
    [self.title_label sizeToFit];
    
    
    [self hidePicker:NO];
    
    array_step_edit_data = @[
    @{@"name_step":@"*Имя",@"id":@"1"},
    @{@"name_step":@"Фамилия",@"id":@"2"},
    @{@"name_step":@"*Страна",@"id":@"3"},//
    @{@"name_step":@"Регион",@"id":@"4"},//
    @{@"name_step":@"*e-mail",@"id":@"5"},
    @{@"name_step":@"*Адресс",@"id":@"6"},
    @{@"name_step":@"*Город",@"id":@"7"},
    @{@"name_step":@"Телефон",@"id":@"8"},
    @{@"name_step":@"Подписка на новости магазина",@"id":@"9"}
    ];
    
    array_step_edit_password = @[
    @{@"name_step":@"Текущий пароль",@"id":@"21"},
    @{@"name_step":@"Новый пароль",@"id":@"22"},
    @{@"name_step":@"Подтвердите новый пароль",@"id":@"23"},
    ];


    [self.button_resave setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.button_resave setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
}





- (IBAction)segmentSwitch:(id)sender {
    UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
    NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
    if (selectedSegment == 0) {
        NSLog(@"Личные данные");
        current_change_data = YES;
    }
    else{
        current_change_data = NO;
        NSLog(@"Пароль");
    }
    [self.tableView reloadData];
}






#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (current_change_data) {
        return [array_step_edit_data count];
    }else{
        return [array_step_edit_password count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"register_cell";
    
    
    static NSString *CellIdentifier_s = @"register_cell_subscribe";
    register_cell *cell_subscribe = nil;
    
    cell_subscribe = (register_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier_s];
    if(!cell_subscribe)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"register_cell_subscribe" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[register_cell class]])
            {
                cell_subscribe = (register_cell *)currentObject;
                break;
            }
        }
    }
    
    
    register_cell *cell = nil;
    cell = (register_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"register_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[register_cell class]])
            {
                cell = (register_cell *)currentObject;
                break;
            }
        }
    }
    cell.name_steps.hidden = NO;
    cell.conf_pass.hidden = YES;
    int id_cell;
    if (current_change_data) {
        id_cell = [[[array_step_edit_data objectAtIndex:indexPath.row] objectForKey:@"id"] integerValue];
        
        switch (id_cell) {
            case 1:{
                cell.text_field.text = text_name;
                break;}
            case 2:{
                cell.text_field.text = text_second_name;
                break;}
            case 3:{
                cell.text_field.text = text_strana;
                break;}
            case 4:{
                cell.text_field.text = text_region;
                break;}
            case 5:{
                cell.text_field.text = text_email;
                break;}
            case 6:{
                cell.text_field.text = text_adress;
                break;}
            case 7:{
                cell.text_field.text = text_town;
                break;}
            case 8:{
                cell.text_field.text = text_telephone;
                break;}
            case 9:{
                cell_subscribe.name_steps.text = [[array_step_edit_data objectAtIndex:indexPath.row] objectForKey:@"name_step"];
                cell_subscribe.subscribe.on = subscribe_user;
                cell_subscribe.subscribe.tag = 50;
                [cell_subscribe.subscribe addTarget:self action:@selector(changeSubscribe:) forControlEvents:UIControlEventValueChanged];
                cell_subscribe.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell_subscribe;
                break;}
            default:
                break;
        }
        
        if (id_cell==3 || id_cell==4) {
            cell.button_cell.tag = id_cell;
            cell.button_cell.hidden = NO;
            [cell.button_cell addTarget:self action:@selector(touchOpenPicker:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            cell.button_cell.hidden = YES;
        }
        
        
        
        NSString* txt1 = [[array_step_edit_data objectAtIndex:indexPath.row] objectForKey:@"name_step"];
        NSMutableAttributedString* attrStr1 = [NSMutableAttributedString attributedStringWithString:txt1];
        [attrStr1 setFont:[UIFont fontWithName:@"Verdana" size:14]];
        [attrStr1 setTextColor:[UIColor colorWithRed:39.0/255.0 green:38.0/255.0 blue:32.0/255.0 alpha:1]];
        NSRange range = [txt1 rangeOfString:@"*"];
        [attrStr1 setTextColor:[UIColor redColor] range:range];
        cell.name_steps.attributedText = attrStr1;
        
        
        //cell.name_steps.text = [[array_step_edit_data objectAtIndex:indexPath.row] objectForKey:@"name_step"];

    }else{
        cell.button_cell.hidden = YES;
        id_cell = [[[array_step_edit_password objectAtIndex:indexPath.row] objectForKey:@"id"] integerValue];
        [cell.name_steps setFont:[UIFont fontWithName:@"Verdana" size:13]];
        //cell.name_steps.backgroundColor = [UIColor redColor];
        switch (id_cell) {
            case 21:{
                cell.text_field.text = text_old_pass;
                break;}
            case 22:{
                cell.text_field.text = text_new_pass;
                break;}
            case 23:{
                cell.text_field.text = text_new_pass_comf;
                cell.name_steps.hidden = YES;
                cell.conf_pass.text = [[array_step_edit_password objectAtIndex:indexPath.row] objectForKey:@"name_step"];
                [cell.conf_pass setFont:[UIFont fontWithName:@"Verdana" size:13]];
                [cell.conf_pass setTextColor:[UIColor colorWithRed:39.0/255.0 green:38.0/255.0 blue:32.0/255.0 alpha:1]];
                cell.conf_pass.hidden = NO;
                break;}
            default:
                break;
        }
        
        
        cell.name_steps.text = [[array_step_edit_password objectAtIndex:indexPath.row] objectForKey:@"name_step"];
    }
    
    
    cell.text_field.tag = id_cell;
    cell.text_field.delegate = self;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}







#pragma mark -
#pragma mark Keyboard Handling

- (void)keyboardWillShow:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
	keyboardIsShowing = YES;
	[self resizeViewControllerToFitScreen];
}

- (void)keyboardWillHide:(NSNotification *)note {
	keyboardIsShowing = NO;
	keyboardBounds = CGRectMake(0, 0, 0, 0);
	[self resizeViewControllerToFitScreen];
}


- (void)resizeViewControllerToFitScreen {
	// Needs adjustment for portrait orientation!
	CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
	CGRect frame = self.tableView.frame;
	frame.size.height = applicationFrame.size.height - self.tabBarController.tabBar.frame.size.height - self.navigationController.navigationBar.frame.size.height;
    
	if (keyboardIsShowing)
		frame.size.height -= (keyboardBounds.size.height-50);
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:0.3f];
	self.view.frame = frame;
	[UIView commitAnimations];
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    
    [textField resignFirstResponder];
    return YES;
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    int id_cell = textField.tag;
    
    NSString *text;
    if (range.length<1) {
        
        text = [NSString stringWithFormat:@"%@%@",textField.text,string];
    }else{
        text = [textField.text substringToIndex:[textField.text length] - 1];
        //text = [NSString stringWithFormat:@"%@",textField.text];
    }
    
    
    
    if (current_change_data) {
        switch (id_cell) {
            case 1:{
                text_name = text;
                break;}
            case 2:{
                text_second_name = text;
                break;}
            case 3:{
                text_strana = text;
                break;}
            case 4:{
                text_region = text;
                break;}
            case 5:{
                text_email = text;
                break;}
            case 6:{
                text_adress = text;
                break;}
            case 7:{
                text_town = text;
                break;}
            case 8:{
                text_telephone = text;
                break;}
            default:
                break;
        }

    }else{
        switch (id_cell) {
            case 21:{
                text_old_pass = text;
                break;}
            case 22:{
                text_new_pass = text;
                break;}
            case 23:{
                text_new_pass_comf = text;
                break;}
            default:
                break;
        }

    }
        
    return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField {
    
    [self hidePicker:showed_picker];
    if (textField.tag==2) {
        //[test_textField resignFirstResponder];
        //[textField resignFirstResponder];
        //[self performSelector:@selector(openPicker:) withObject:self afterDelay:0.5];
    }
    test_textField = textField;
    
    CGPoint pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:pnt];
    
    [self performSelector:@selector(aaaap:) withObject:path afterDelay:0.1];
}

-(void)aaaap:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

-(void)upScrolFromPicker:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView
numberOfRowsInComponent:(NSInteger)component
{
    if (id_button==3) {
        return sortedArrayCountry.count;
    }else{
        return sortedArrayRegion.count;
    }
    
}

- (NSString *)pickerView:(UIPickerView *)thePickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    if (id_button==3) {
        return [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
    }else{
        return [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
    }
}



-(void)touchOpenPicker:(id)sender{
    [test_textField resignFirstResponder];
    [self openPicker:self];
    
    UIButton *button = (UIButton*)sender;
    id_button = [sender tag];
    
    CGPoint pnt = [self.tableView convertPoint:button.bounds.origin fromView:button];
    pnt = CGPointMake(pnt.x, pnt.y+90);
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:pnt];
    
    [pickerView reloadAllComponents];
    [self performSelector:@selector(upScrolFromPicker:) withObject:path afterDelay:0.1];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (id_button==3) {
        text_strana = [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
        current_id_country_ = [[[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_id"] integerValue];
        
        if (last_country_id_!=current_id_country_) {
            text_region= @"";
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:id_button inSection:0];
            NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        }
        
        [self sortRegionWithIdCountry:current_id_country_];
        
    }else{
        
        last_zone_id_ = [[[sortedArrayRegion objectAtIndex:row] objectForKey:@"zone_id"] integerValue];
        text_region = [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
    }
    
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:id_button-1 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    
   // NSLog(@"index reload = %i",indexPath.row);
    
}


-(IBAction)openPicker:(id)sender{
    if ([sortedArrayCountry count]>0 && [sortedArrayRegion count]>0) {
        [self hidePicker:NO];
        showed_picker = YES;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, self.view.frame.size.height - pickerView.frame.size.height/2);
        [UIView commitAnimations];
    }
}


-(void)hidePicker:(BOOL)animate{
    showed_picker = NO;
    if (animate) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
        [UIView commitAnimations];
    }else{
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (showed_picker) {
        [self hidePicker:YES];
    }
    [test_textField resignFirstResponder];
}



-(IBAction)changeSubscribe:(id)sender{
    UISwitch *switch_view = (UISwitch*)sender;
    //NSLog(@"state = %i",switch_view.on);
    subscribe_user = switch_view.on;
}




-(void)sortCountryFromArray:(NSArray*)array_data{
    if ([array_data count]>0) {
        [sortedArrayRegion removeAllObjects];
        NSSet * set = [NSSet setWithArray:[array_data valueForKey:@"country_id"]];
        NSMutableArray *sorted_array = [[set allObjects] mutableCopy];
        
        for (int j =0; j<[sorted_array count]; j++) {
            for (int i =0; i < [array_data count]; i++) {
                if ([[[array_data objectAtIndex:i] objectForKey:@"country_id"] integerValue]==[[sorted_array objectAtIndex:j]  integerValue]) {
                    NSString *id_country = [[array_data objectAtIndex:i] objectForKey:@"country_id"];
                    NSString *name_country = [[array_data objectAtIndex:i] objectForKey:@"country_name"];
                    NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
                    NSDictionary *dict = @{@"country_id" : id_country, @"country_name" : name_country,@"zone_id" : id_zone};
                    [sortedArrayCountry addObject:dict];
                    break;
                }
            }
        }
        
        if ([sortedArrayCountry count]>0) {
            current_id_country_ = [[[sortedArrayCountry objectAtIndex:0] objectForKey:@"country_id"] integerValue];
            [self sortRegionWithIdCountry:current_id_country_];
        }
        
        //NSLog(@"sortedArrayCountry  = %@",sortedArrayCountry);
        
    }
}


-(void)sortRegionWithIdCountry:(int)id_country{
    [sortedArrayRegion removeAllObjects];
    
    NSDictionary *dict_clear = @{@"country_id" : @"0", @"name_zone":@"",@"zone_id":@"0"};
    [sortedArrayRegion addObject:dict_clear];
    
    for (int i =0; i < [dataLocation count]; i++) {
        if ([[[dataLocation objectAtIndex:i] objectForKey:@"country_id"] integerValue]==id_country) {
            NSString *id_country = [[dataLocation objectAtIndex:i] objectForKey:@"country_id"];
            NSString *name_zone = [[dataLocation objectAtIndex:i] objectForKey:@"name_zone"];
            NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
            NSDictionary *dict = @{@"country_id" : id_country, @"name_zone" : name_zone,@"zone_id" : id_zone};
            [sortedArrayRegion addObject:dict];
        }
    }
    last_country_id_ = id_country;
    //NSLog(@"sortedArrayRegion = %@",sortedArrayRegion);
}

-(void)getLocationData{
    
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/get_location.php"]; // куда отправлять
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection_locate = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_locate) {
        self.locateData = [NSMutableData data];
    }
}





-(void)parseCustomerData{
    NSString* params = [NSString stringWithFormat:@"id_customer=%i",[Singleton sharedMySingleton].user_id];
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/get_user.php"];     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
    
    connection_customer_data = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_customer_data) {
        self.customer_data = [NSMutableData data];
    }
}










- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_locate) {
        [locateData appendData:data];
    }else{
        if (connection == connection_customer_data) {
            [customer_data appendData:data];
        }else{
            if (connection == connection_send_data) {
                [send_data_user appendData:data];
            }
        }
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (connection == connection_locate) {
        [self parseJSON:locateData IsUserData:NO];
    }else{
        if (connection == connection_customer_data) {
            [self parseJSON:customer_data IsUserData:YES];
        }else{
            if (connection == connection_send_data) {
                [self parseResultAfterSending:send_data_user];
            }

        }
    }
}


#pragma mark parse JSON result

-(void)parseResultAfterSending:(NSData*)data{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    NSString *data_content = [json objectForKey:@"message"];
    
    if ([requestResultAutorization integerValue]==1){
        [Singleton sharedMySingleton].user_name = text_name;
        [Singleton sharedMySingleton].user_second_name = text_second_name;
        [Singleton sharedMySingleton].user_adress = text_adress;
        [Singleton sharedMySingleton].user_city = text_town;
        [Singleton sharedMySingleton].user_id_country = [NSString stringWithFormat:@"%i",  last_country_id_];
        [Singleton sharedMySingleton].user_id_zone = [NSString stringWithFormat:@"%i",  last_zone_id_];
        
    }
    
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:data_content];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
    }];
    [alert show];
    [self removeActivityView];
}



-(void)parseJSON:(NSData*)data IsUserData:(BOOL)parse_user{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    
    
    
    
    
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    NSArray * array_data = [json objectForKey:@"message"];
    
    
        if ([requestResultAutorization integerValue]==1) {
            
            if (parse_user) {
                if ([array_data count]>0) {
                    
                    text_name = [[array_data objectAtIndex:0] objectForKey:@"firstname"];
                    
                    text_second_name = [[array_data objectAtIndex:0] objectForKey:@"lastname"];
                    
                    text_region = [[array_data objectAtIndex:0] objectForKey:@"region"];
                    
                    text_email = [[array_data objectAtIndex:0] objectForKey:@"email"];
                    
                    text_adress = [[array_data objectAtIndex:0] objectForKey:@"street_adress"];
                    
                    text_strana = [[array_data objectAtIndex:0] objectForKey:@"countries_name"];
                    text_telephone = [[array_data objectAtIndex:0] objectForKey:@"telephone"];
                    
                    text_town = [[array_data objectAtIndex:0] objectForKey:@"city"];
                    
                    subscribe_user = [[[array_data objectAtIndex:0] objectForKey:@"newsletter"] integerValue];
                    
                    last_country_id_ = [[[array_data objectAtIndex:0] objectForKey:@"country_id"]integerValue];
                    last_zone_id_ = [[[array_data objectAtIndex:0] objectForKey:@"zone_id"]integerValue];///
                    
                    parsed_password = [[array_data objectAtIndex:0] objectForKey:@"password"];
                    
                    [self.tableView reloadData];
                                      
                }else{
                    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
                    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                    }];
                    [alert show];
                }
            }else{
                if ([array_data count]>0) {
                    dataLocation = array_data;
                    [self sortCountryFromArray:array_data];
                }else{
                    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
                    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                    }];
                    [alert show];
                }
            }
             
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            [alert show];
        }
    
    
    
    [self removeActivityView];
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(getLocationData) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}

#pragma mark Dejal activity

- (void)displayActivityView
{
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark

-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}




-(IBAction)changesData:(id)sender{
    if (current_change_data) {
        [self SendDataChanges];
    }else{
        [self SendPasswordChanges];
    }
}

-(void)SendPasswordChanges{
    
    //NSLog(@"OLD PASS = %@",text_old_pass);
    //NSLog(@"New Pass = %@",text_new_pass);
    //NSLog(@"confirm new pass = %@",text_new_pass_comf);
    if ([text_new_pass length]>5) {
        
        
        NSString *pass = [text_old_pass MD5];
        
        if ([parsed_password isEqualToString:pass]) {
            if ([text_new_pass isEqualToString:text_new_pass_comf]) {
                
                /////////// SEND
               
                NSString * editPassword = @"1";
                NSString* params = [NSString stringWithFormat:@"id_customer=%i&password=%@&editPassword=%@",[Singleton sharedMySingleton].user_id,[text_new_pass MD5] ,editPassword]; // задаем параметры POST запроса
                

                //NSLog(@"params = %@",params);
                
                
                NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/edit_user_data.php"]; // куда отправлять
                NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
                request.HTTPMethod = @"POST";
                request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
                
                connection_send_data = [NSURLConnection connectionWithRequest:request delegate:self];
                [self displayActivityView];
                if (connection_send_data) {
                    self.send_data_user = [NSMutableData data];
                }

            }else{
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Не правильное подтверждение пароля"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                }];
                
                [alert show];
            }
            
        }else{
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Не правильно заполнен текущий пароль!"];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            }];
            
            [alert show];
        }
        
    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Длинна пароля должна быть не меньше 6 символов"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        
        [alert show];
    }
    
    
}


-(void)SendDataChanges{
    //NSLog(@"REGISTER DATA");
    //NSLog(@"text_name! = %@",text_name);
    //NSLog(@"text_second_name = %@",text_second_name);
    //NSLog(@"text_email! = %@",text_email);
    //NSLog(@"text_adress! = %@",text_adress);
    //NSLog(@"text_town! = %@",text_town);
    //NSLog(@"text_region = %@",text_region);
    //NSLog(@"text_strana! = %@",text_strana);
    //NSLog(@"text_telephone = %@",text_telephone);
    //NSLog(@"subscribe_user = %i",subscribe_user);
    
    if ([text_name length]>0 && [text_email length]>0 && [text_adress length]>0 && [text_town length]>0 && [text_strana length]>0) {
        /// SEND
        //$id_customer,$first_name,$last_name,$email,
        //$telephone,$streat_adress,$newsletter,$city,
        //$id_country,$id_zone,$name_zone,$name_country
//$editPassword
        NSString* params;
        NSString * editPassword = @"2";
        if (current_change_data) {
            editPassword = @"2";
            params = [NSString stringWithFormat:@"id_customer=%i&first_name=%@&last_name=%@&email=%@&telephone=%@&streat_adress=%@&newsletter=%i&city=%@&id_country=%i&id_zone=%i&name_zone=%@&name_country=%@&editPassword=%@",[Singleton sharedMySingleton].user_id,text_name,text_second_name,text_email,text_telephone,text_adress,subscribe_user,text_town,last_country_id_,last_zone_id_,text_region,text_strana,editPassword]; // задаем параметры POST запроса
        }else{
            editPassword = @"1";
            params = [NSString stringWithFormat:@"id_customer=%i&password=%@&editPassword=%@",[Singleton sharedMySingleton].user_id,text_new_pass,editPassword]; // задаем параметры POST запроса
        }
        
        
        //NSLog(@"params = %@",params);
        
        
        NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/edit_user_data.php"]; // куда отправлять
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
        
        connection_send_data = [NSURLConnection connectionWithRequest:request delegate:self];
        [self displayActivityView];
        if (connection_send_data) {
            self.send_data_user = [NSMutableData data];
        }

                
        
    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Заполнены не все обязательные поля (*)."];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        }];
        
        [alert show];
    }
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
